var clipboard;

/**
 * calculates the sum of elements
 *
 * param string base_id - basis of elements' name
 * param string tag_name - in which tags we calculate
 * param string sum_id - where put the sum
*/
function SumElements(base_id, tag_name, sum_id)
{
	var elems = document.getElementsByTagName(tag_name);
	sum = 0;
	
	for(i=0; i<elems.length; i++)
	{ 
		if ((elems[i].id.match(base_id) != null)) // && (elems[i].disabled != true)
		{	
			sum += Number(elems[i].value);
		}
	}
	document.getElementById(sum_id).value = sum;
} 

/*
* submits the given form by pressing 'Ctrl + Enter'
* param object e event
* param object form current form
*/
function SubmitWithCtrlEnter(e, form)
{
	if (((e.keyCode == 13) || (e.keyCode == 10)) && (e.ctrlKey == true)) form.submit();
}

/**
 * popup window
 *
 * param string url - url
*/
function popupWindow(url) 
{
  window.open(url,'_blank','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no,width=400,height=400,screenX=150,screenY=150,top=150,left=150')
}


/**
 * makes print preview
 *
 * param string id element which innerHTML will be printed
*/
function printPage(id,title)
{
	document.getElementById('report_title').value = title;
	document.getElementById('print_preview').value = document.getElementById(id).innerHTML;
	document.getElementById('form_preview').submit();
}

/**
 * validates given field towards min/max values
 *
 * param string elem field
 * param string min minimal value
 * param string max maximal value
*/
function ValidateMinMax(elem, min, max)
{
	if ((min!='-')&&((elem.value<min)||(elem.value==''))) elem.value = min;
	if ((max!='-')&&(elem.value>max)) elem.value = max;
}

/**
 * show/hides the specified tags with the specified id
 *
 * param string field field id
 * param string tag_name tag name
*/
function show_hide_tags(field, tag_name, show_only)
{
	var trs = document.getElementsByTagName(tag_name);
	for (i = 0; i < trs.length; i++)
	{
		if(trs[i].id==field)
		{
			if(trs[i].style.display=='none')
			{
				trs[i].style.display='';
			}
			else
			{
				trs[i].style.display='none';
			}
		}
	}
}

/**
 * shows the specified tags
 *
 * param string tag_name tag name
*/
function show_tags(tag_name)
{
	var trs = document.getElementsByTagName(tag_name);
	for (i = 0; i < trs.length; i++)
	{
		if(trs[i].style.display=='none')
		{
			trs[i].style.display='';
		}
	}
}

/**
 * Used in helper MultiListboxRow
 * Shows multiselect list boxes
 * param string child_id id of the child element
 * param string div_id id of the div element
 * param string fieldname name of the field
 * param string id2fill if of the field to be filled
*/

function show_child(child_id, div_id, fieldname, id2fill, hid_prefix, div_prefix)
{				 	 
	var select = document.getElementsByTagName('DIV');							 
	var selects = document.getElementsByTagName('SELECT');							 
	var idx = 0;
		

	// fill the hidden field
	document.getElementById(fieldname).value = child_id;
	
	if(typeof(hid_prefix) == 'undefined' || hid_prefix == '')	
		hid_prefix = 'undefined';
	
	if(typeof(div_prefix) == 'undefined' || div_prefix == '')		
		str_id = 'parent_'+div_id;
	else
		str_id = div_prefix+'parent_'+div_id;
	
	// search selected div
	for(j = 0; j< select.length; j++)
	{		
		if(select[j].id == str_id)
		{
			idx = j;								 		
			break;
		}
	}
	
	// go through divs
	for( k = (idx+1); k < select.length; k++)
	{
		str_select_id = select[k].id;	

	  //if( document.getElementById(str_select_id) == null) continue;
		
		// if element is not root and element exists
		if( str_select_id.indexOf('parent_') >= 0 && str_select_id != div_prefix+'parent_0' && str_select_id != str_id && document.getElementById(str_select_id) != null )
		{								 				
				// hide element									
				if(hid_prefix !='undefined')				
				{
					if(document.getElementById(hid_prefix) != null && document.getElementById(hid_prefix).value == div_prefix && str_select_id.indexOf(div_prefix) >=0)
					{															
						document.getElementById(str_select_id).style.display = 'none';
					}
				}	
				else 
					document.getElementById(str_select_id).style.display = 'none';

				// deselect
				var x=document.getElementById("select_"+str_select_id);			 
			  for (i=0;i<x.length;i++)
			  {
			   x.options[i].selected = false;
			  }						
		}
	}
	
	
	// if element exists show it
	if(document.getElementById(div_prefix+'parent_'+child_id) != null)
	{		
		document.getElementById(div_prefix+'parent_'+child_id).style.display = 'block';							
		var pos = document.getElementById(div_prefix+'parent_'+child_id).offsetLeft;
		document.getElementById(div_prefix+'parent_'+child_id).style.left = pos;		
		document.getElementById('opt_'+child_id).selected = true;
	}
	else
	{	
		document.getElementById(div_prefix+'parent_'+div_id).style.display = 'block';
		document.getElementById('opt_'+child_id).selected = true;
	}	
	// we define field where will be copy data from list box
	
	if( id2fill != '')
	{	
		document.getElementById(id2fill).value = '';					 		 	
								 		 	
		for(i = 0; i< selects.length; i++ )
		{	
			div = selects[i].id.replace('select_', ''); 
			
			if( document.getElementById(div) != null  && document.getElementById(div).style.display == 'block' && document.getElementById(div) != '')
			{	
				selectBox = document.getElementById(selects[i].id);
				index = selectBox.selectedIndex;
				text = selectBox.options[index].text;
				
				// get text from list box and fill the field
				if( document.getElementById(id2fill).value == '' )						 									
					document.getElementById(id2fill).value += text;
				else
				{	
					if(document.getElementById(id2fill).value.indexOf(text) == -1)
						document.getElementById(id2fill).value += '->' + text;
				}
				str_child = 'select_'+div_prefix+'parent_'+child_id;	
				
				// we found the last element needed to select
				if( selects[i].id == str_child )
				{
					document.getElementById(str_child).selected = true;
					break;
				}
			}
		}						 												 	
	}	
}

/**
 * Returns caret to the beginning of the input field
 * param object input field object
*/
function MoveCaretToStart(inputObject)
{ 
  var ver = navigator.appVersion;
  if (ver.indexOf('MSIE') != -1)
  { 
   if (inputObject.createTextRange)
   {
      var r = inputObject.createTextRange();
      r.collapse(true);
      r.select();
   }
  }
  else 
  { 
   if (inputObject.selectionStart)
   {
     inputObject.setSelectionRange(0,0);
     inputObject.focus();
   }
  }
}

function moveElement(parent, child_id)
{
	var child = document.getElementById(child_id);
	if(child)
	{
	var child_1 = child.cloneNode(true);

	parent.parentNode.removeChild(child);	

	parent.parentNode.appendChild(child_1);
	}
}

/**
 * replaces 'Inactive' from image src attribute by the specified id
 *
 * param string id image id
*/
function SetImagesActiveById(id)
{
	var trs = document.getElementsByTagName('img');
	for (i = 0; i < trs.length; i++)
	{
		if(trs[i].id==id)
		{
			trs[i].src = trs[i].src.replace('Inactive', ''); 
		}
	}	
}

/**
 * enables/disables the input tags with the specified id
 *
 * param string field field id
*/
function enable_disable_tags(field)
{
	var trs = document.getElementsByTagName('input');
	for (i = 0; i < trs.length; i++)
	{
		if(trs[i].id==field)
		{
			if(trs[i].disabled)
			{
				trs[i].removeAttribute('disabled');
			}
			else
			{
				trs[i].disabled='disabled';
			}
		}
	}
}

/**
 * Adds/Removes values from the string with the given id
 *
 * param string search value
 * param string string id
*/	
function AddRemoveValues(value, id)
{
	field = document.getElementById(id);
	if (field.value.search(value)!='-1')
	{ 
		str = field.value;
		field.value = field.value.replace(value, "");
	}
	else
	{
		field.value = field.value + "," + value;
	}

	if (field.value.substring(0,1) == ",")
	{
		field.value = field.value.substring(1);
	}
}

/**
 * shows/hides the box, e.g. filter
 *
 * param integer field_id table width
 * param integer controller controller name for the AJAX
 * param integer action action name for the AJAX
 * param integer image_id plus/minus image id
 * param integer plus_image path to the plus image
 * param integer minus_image path to the plus image
*/	
function ShowHideBox(field_id, controller, action, image_id, plus_image, minus_image)
{
	element = document.getElementById(field_id);
	if(element.style.display=='none')
	{
		element.style.display='';
		document.getElementById(image_id).src = minus_image;
		SendValues("/main/" + action + "/" + controller + "/1"); 
		
	}
	else
	{
		element.style.display='none';
		document.getElementById(image_id).src = plus_image;
		SendValues("/main/" + action + "/" + controller + "/0"); 
	}	
}

/**
 * updates date depending on its components
 *
 * param string id element id
*/	
function updateDate(id)
{
	fullDate = document.getElementById(id);
	day = document.getElementById(id+'_day');
	month = document.getElementById(id+'_month');
	year = document.getElementById(id+'_year');

	if (document.getElementById(id+'_hour')) hour = document.getElementById(id+'_hour');
	if (document.getElementById(id+'_minute')) minute = document.getElementById(id+'_minute');
	
	if (year.value!='') fullDate.value = day.value + '-' + month.value + '-' + year.value;
	else fullDate.value = '';
	
	if (document.getElementById(id+'_hour')) fullDate.value += ' ' + hour.value + ':' + minute.value + ':00';
}

/**
 * updates time depending on its components
 *
 * param string id element id
*/	
function updateTime(id)
{
	fullTime = document.getElementById(id);

	if (document.getElementById(id+'_hour')) hour = document.getElementById(id+'_hour');
	if (document.getElementById(id+'_minute')) minute = document.getElementById(id+'_minute');
	
	fullTime.value = Number(hour.value*60) + Number(minute.value);
}
	
var f=0;
   /**
 * adds an input field to the specified parent element
 *
 * param string id parent element id
*/	
function addInput(id, input_name, input_type, input_class)
{
	//default values
	input_name = typeof(input_name) != 'undefined' ? input_name : 'attachment';
	input_type = typeof(input_type) != 'undefined' ? input_type : 'file';
	input_class = typeof(input_class) != 'undefined' ? input_class : 'file';
	
	f++;
	elem = document.getElementById(id)
	br = document.createElement('BR');
	input = document.createElement('INPUT');
	input.setAttribute('type', input_type);
	input.className = input_class;
	input.name = input_name+'[' + f +']';
	input.onchange = function () { addInput(id); };
	elem.appendChild(br);	
	elem.appendChild(input);
}

/**
 * Creating print preview for source table
 *
 * param string id table source id
 * param string title title for print preview
 * param string image_url images url
*/
function makePrint(id,title,image_url)
{
	var new_table = document.createElement("table");
	new_table.id = 'print_table';
	new_table.width = '100%';
	new_table.cellPadding = 0;	
	new_table.cellSpacing = 0;
	var tblBody = document.createElement("tbody");
	var tblBody_2 = document.createElement("tbody");
	var row_2 = document.createElement("tr");
	var cell_0 = document.createElement("td");
 			
	table = document.getElementById(id);
	rows = table.rows;
 	for(i = 0; i < rows.length; i++)
 	{
        var row = document.createElement("tr");
        var cell_1 = document.createElement("td");
        cell_1.style.fontSize="12px";
        cell_1.width ='30%';
	    var cell_2 = document.createElement("td");
	    cell_2.style.fontSize="12px";
	    var cell_3 = document.createElement("td");
	    cell_3.setAttribute('class', 'label');
	    cell_3.width = 15;
	    var cell_4 = document.createElement("td");
	    cell_4.setAttribute('class', 'label');
	    cell_4.width = 20;
	    
	    cell_1.style.borderLeft = '1px solid #FFF';
	    cell_2.style.borderLeft = '1px solid #FFF';
	    cell_2.style.borderRight = '1px solid #FFF';
	    cell_1.style.borderBottom = '1px solid #FFF';
	    cell_2.style.borderBottom = '1px solid #FFF';
	    
	    if (i==0)
	    {cell_1.style.borderTop = '1px solid #FFF';
	     cell_2.style.borderTop = '1px solid #FFF';}
   
	    
	    var button_down = document.createElement("input");
	    button_down.type = 'button';
	    button_down.style.background = "url("+image_url+"arrow_down.gif) no-repeat";
	    button_down.style.border = '0';
	    button_down.style.padding = '0';
	    button_down.style.width = 11;
	    button_down.style.height = 8;
	    button_down.setAttribute('onClick', 'moverow(this.parentNode.parentNode , 1 )');
	    button_down.onclick = function() {moverow( 'this.parentNode' , 1 )};
	
	    //--
	    var button_up = document.createElement("input");
	    button_up.type = 'button';
	    button_up.style.background = "url("+image_url+"arrow_up.gif) no-repeat";
	    button_up.style.background.repeat = 'no-repeat';
	    button_up.style.border = '0';
	    button_up.style.padding = '0';
	    button_up.style.width = 11;
	    button_up.style.height = 8;
	    button_up.setAttribute('onClick', 'moverow(this.parentNode.parentNode, -1 )');
	    button_up.onclick = function() {moverow( 'this.parentNode' , -1 )};
	    
		var checkbox = document.createElement("input");
	    checkbox.type = 'checkbox';
	    checkbox.name = rows[i].cells[0].innerHTML;
	    checkbox.setAttribute('class', 'checkbox');
	    checkbox.defaultChecked=true;
   
	    
        cell_4.appendChild(checkbox);
	    
	    
	    cell_3.appendChild(button_up);
	    cell_3.appendChild(button_down);
	    var cell_value = 0;
	    
	    cell_1.innerHTML = rows[i].cells[0].innerHTML;
	    if(	rows[i].cells[1].firstChild.type == 'select-one')
	    {
		    options = rows[i].cells[1].firstChild.options;
			for(j = 0; j < options.length; j++)
		 	{
		 		 if (options[j].selected) 
		         cell_2.innerHTML = options[j].innerHTML;
		 	}
	    }
	    else
	    {
	    	cell_value = rows[i].cells[1].childNodes[1].childNodes[1].rows[0].cells[0].firstChild.value;
	    	if(cell_value=='')
	    	cell_value = '&nbsp;';
	    	cell_2.innerHTML = cell_value;
	    }

	    row.appendChild(cell_4);
	   	row.appendChild(cell_1);
	    row.appendChild(cell_2);
	    row.appendChild(cell_3);
	    tblBody.appendChild(row);
        
        
 	}
 	new_table.appendChild(tblBody);
 	cell_0.appendChild(new_table);
 	row_2.appendChild(cell_0);
 	tblBody_2.appendChild(row_2);
 	
 	document.getElementById('report_title').value = title;
	document.getElementById('print_preview').value = tblBody_2.innerHTML;
	document.getElementById('form_preview').submit();
}

/**
 * searches the data in the field with the given id and displays values in a list box
 *
 * param integer select_id
*/		
function FastSearch(select_id)
{
  if (navigator.appName == "Microsoft Internet Explorer")
  {
  	FastSearchExplorer(select_id);
  	return;
  }

  	var criterium = document.getElementById('search_field_'+select_id).value;
	var roll = document.getElementById(select_id);
	var list_size=0;
	
	if (criterium=='')
	{
		for (i = 1; i < roll.options.length; i++)
		{
			roll.options[i].style.display = '';
		}
		roll.size = 1;
	}
	else
	{
		for (i = 0; i < roll.options.length; i++)
		{
			if (roll.options[i].text.toLowerCase().match(criterium.toLowerCase())==null)
			{
				roll.options[i].style.display = 'none';
			}
			else
			{
				roll.options[i].style.display = '';
				list_size++;
			}
		}
	
		if (list_size<=5) 
		{
			roll.size = list_size+1;
		}
		else roll.size = 5;
	}
}


/**
 * searches the data in the field with the given id and displays values in a list box (for IE)
 *
 * param string select_id
*/
function FastSearchExplorer(select_id)
{
	var criterium = document.getElementById('search_field_'+select_id).value;
	var roll = document.getElementById(select_id);
	var list_size=0;
	var roll_list  = new Array(new Array(),new Array());
	var show_roll_list  = new Array(new Array(),new Array());
	if (criterium=='')
	{
		for (i = 1; i < roll.options.length; i++)
		{
			roll.options[i].style.display = '';
		}
		roll.size = 1;
	}
	else
	{
		var j = 0;
		var m = 0;	
	
		for (i = 0; i < roll.options.length; i++)
		{
			if (roll.options[i].text.toLowerCase().match(criterium.toLowerCase())==null)
			{
				roll_list[0][m] = roll.options[i].value;
				roll_list[1][m] = roll.options[i].text;
				m++;
			}
			else
			{
				list_size++;
				show_roll_list[0][j] = roll.options[i].value;
				show_roll_list[1][j] = roll.options[i].text;
				j++;
			}
		}

		while(roll.length > 0) {roll.remove(0)};
		for (i = 0; i <show_roll_list[0].length; i++)
		{ 
			var new_opt = new Option(show_roll_list[1][i],show_roll_list[0][i]);
			roll.options[roll.options.length]=new_opt;
		}

		for (i = 0; i <roll_list[0].length; i++)
		{
			var new_opt = new Option(roll_list[1][i],roll_list[0][i]);
			roll.options[roll.options.length]=new_opt;
		}		
		if (list_size<=5) 
		{
			roll.size = list_size+1;
		}
		else roll.size = 5;
	}
	
}


/**
 * checks/unchecks checkboxed
 *
 * param string field - field id
 * param boolean cmb to check or uncheck
*/
function CheckAllBoxes(field, cmb)
{
	var checks = document.getElementsByTagName("INPUT");
	for (i = 0; i < checks.length; i++)
	if(checks[i].id == field )
	checks[i].checked = cmb ;
}

/**
 * checks if at least one of the checkboxes is checked
 *
 * param string field_id - field id
 * param string form_id - form id
 * param string text - text to display if no checkboxes are checked
*/
function areChecked(field_id, form_id, text)
{
	var checks = document.getElementsByTagName("INPUT");
	var flag = 0;
	for (i = 0; i < checks.length; i++)
	if(checks[i].id == field_id)
		if (checks[i].checked == true) flag = 1;
	
	if (flag==0) alert(text);
	else document.getElementById(form_id).submit()
}

/**
 * trims all spaces
 *
 * param string string - string to parse
 * param string other chars to be removed
 * return parsed string
*/
function trim(str, chars) 
{
    return ltrim(rtrim(str, chars), chars);
}

/**
 * trims left spaces
 *
 * param string string - string to parse
 * param string other chars to be removed
 * return parsed string
*/
function ltrim(str, chars) 
{
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

/**
 * trims right spaces
 *
 * param string string - string to parse
 * param string other chars to be removed
 * return parsed string
*/
function rtrim(str, chars) 
{
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

/**
 * gets object position
 *
 * param object obj - DOM object
 * return position
*/
function findPos(obj) 
{
	var curtop = 0;
	if (obj.offsetParent) {
		do {
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return curtop;
}

function ValidateRegExp(obj, expression, text)
{
	regExp = new RegExp(expression);
	if (!regExp.test(obj.value)) alert(text);
}

/**
 * checks if the given object is of proper type
 * param object obj - object to explore
 * param string type - data type
*/
function checkNumber(obj, type) 
{
	//validates vs integer
	if(type == 'int')
	{
		if(isNaN(parseInt(obj.value))) 
			obj.value = ''; 
		else 
			obj.value = parseInt(obj.value);
	}
	//validates vs float
	else if(type == 'float')
	{
		obj.value = obj.value.replace(',', '.');
		if (obj.value.substr(obj.value.length-1, 1) != '.')
		{
			if(isNaN(parseFloat(obj.value))) 
				obj.value = ''; 
			else
				obj.value = parseFloat(obj.value);
		}
		//obj.value = obj.value.replace('.', ',');
	}
}

/**
 * The function will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * param array arr - array,hash(associative array),object
 * param integer level - optional
 * return string dumped_text - the textual representation of the array
*/
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	alert(dumped_text);
}

/**
 * Prompts before a user want to quit the page. Use window.onbeforeunload = PromptBeforeQuit for this purpose/
 * param e event
*/
function PromptBeforeQuit(e) 
{
	if(!e) e = window.event;
	//e.cancelBubble is supported by IE - this will kill the bubbling process.
	e.cancelBubble = true;
	e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog

	//e.stopPropagation works in Firefox.
	if (e.stopPropagation) {
		e.stopPropagation();
		e.preventDefault();
	}
}


/* TAB MENU */

var ddtabmenu={
	disabletablinks: false, ////Disable hyperlinks in 1st level tabs with sub contents (true or false)?
	currentpageurl: window.location.href.replace("http://"+window.location.hostname, "").replace(/^\//, ""), //get current page url (minus hostname, ie: http://www.dynamicdrive.com/)

definemenu:function(tabid, dselected){
	this[tabid+"-menuitems"]=null
	this.addEvent(window, function(){ddtabmenu.init(tabid, dselected)}, "load")
},

showsubmenu:function(tabid, targetitem){
	var menuitems=this[tabid+"-menuitems"]
 for (i=0; i<menuitems.length; i++){
		menuitems[i].className=""
		if (typeof menuitems[i].hasSubContent!="undefined")
			document.getElementById(menuitems[i].getAttribute("rel")).style.display="none"
	}
	targetitem.className="current"
	if (typeof targetitem.hasSubContent!="undefined")
		document.getElementById(targetitem.getAttribute("rel")).style.display="block"
},

isSelected:function(menuurl){
	var menuurl=menuurl.replace("http://"+menuurl.hostname, "").replace(/^\//, "")
	return (ddtabmenu.currentpageurl==menuurl)
},

addEvent:function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
	var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
	if (target.addEventListener)
		target.addEventListener(tasktype, functionref, false)
	else if (target.attachEvent)
		target.attachEvent(tasktype, functionref)
},

init:function(tabid, dselected){
	var menuitems=document.getElementById(tabid).getElementsByTagName("a")
	this[tabid+"-menuitems"]=menuitems
	for (var x=0; x<menuitems.length; x++){
		if (menuitems[x].getAttribute("rel")){
			this[tabid+"-menuitems"][x].hasSubContent=true
			if (ddtabmenu.disabletablinks)
				menuitems[x].onclick=function(){return false}
		}
		else //for items without a submenu, add onMouseout effect
			menuitems[x].onmouseout=function(){this.className=""}
		menuitems[x].onclick=function(){ddtabmenu.showsubmenu(tabid, this);}
		if (dselected=="auto" && typeof setalready=="undefined" && this.isSelected(menuitems[x].href)){
			ddtabmenu.showsubmenu(tabid, menuitems[x])
			var setalready=true
		}
		else if (parseInt(dselected)==x)
			ddtabmenu.showsubmenu(tabid, menuitems[x])
	}
}
}
